package com.example.userservice.service;

import com.example.userservice.common.PageParams;
import com.example.userservice.mapper.AgencyMapper;
import com.example.userservice.model.Agency;
import com.example.userservice.model.User;

import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author ：Anitaxiaofeng
 * @description：
 * @create 2018-06-23
 **/
@Service
public class AgencyService {


    @Autowired
    private AgencyMapper agencyMapper;



    @Value("${file.prefix}")
    private String imgPrefix;

    public Pair<List<User>,Long> getAllAgent(PageParams pageParams) {
        List<User> agents = agencyMapper.selectAgent(new User(), pageParams);
        setImg(agents);
        Long count = agencyMapper.selectAgentCount(new User());
        return ImmutablePair.of(agents,count);

    }


    private void setImg(List<User> users) {
        users.forEach(u->{
            u.setAvatar(imgPrefix+u.getAvatar());
        });
    }


    public User getAgentDetail(Long id) {
        User user = new User();
        user.setId(id);
        user.setType(2);
        List<User> list = agencyMapper.selectAgent(user, new PageParams(1,1));
        setImg(list);
        if(!list.isEmpty()) {
            User agent = list.get(0);
            Agency agency = new Agency();
            agency.setId(agent.getAgencyId().intValue());
            List<Agency> agencies = agencyMapper.select(agency);
            if(!agencies.isEmpty()) {
                agent.setAgencyName(agencies.get(0).getName());
            }
            return agent;
        }
        return null;
    }

}
